package com.fun4admin.auth.service;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class ClientAuthDetailsService extends JdbcClientDetailsService {

    private static final String CLIENT_FIELDS_FOR_UPDATE = "resource_ids, scope, "
            + "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
            + "refresh_token_validity, additional_information, autoapprove";

    private static final String CLIENT_FIELDS = "client_secret, " + CLIENT_FIELDS_FOR_UPDATE;

    private static final String BASE_FIND_STATEMENT = "select client_id, " + CLIENT_FIELDS
            + " from oauth_client_details";

    private static final String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id";

    private static final String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?";


    public ClientAuthDetailsService(DataSource dataSource) {
        super(dataSource);
        setSelectClientDetailsSql(DEFAULT_SELECT_STATEMENT);
        setFindClientDetailsSql(DEFAULT_FIND_STATEMENT);
    }

    /**
     * TODO 使用Redis缓存，但未开启spring缓存开关
     *      缓存空值, 并设置有效期, 等经理决定啊
     * @param clientId
     * @return
     * @throws ClientRegistrationException
     */
    @Cacheable(value = "client:details:", key = "#clientId"/*, unless = "#result == null"*/)
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        return super.loadClientByClientId(clientId);
    }

}
